package it.unibo.refolding.pico.stripchart.ui;

import it.unibo.refolding.common.CommonThings;
import it.unibo.refolding.pico.stripchart.JpHelper;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
import it.unimi.dsi.fastutil.shorts.ShortList;

import java.io.IOException;
import java.nio.file.Path;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import com.google.common.base.Preconditions;

public class JunctionPointsHolder {
	private final Path junctionPointsFile;
	private final ShortList z;

	public final IntList modifiableJunctionPoints;

	public JunctionPointsHolder(Path junctionPointsFile, ShortList z, IntList junctionPoints) {
		this.junctionPointsFile = junctionPointsFile;
		this.z = z;
		Preconditions.checkArgument(CommonThings.increasing(junctionPoints));
		// Make sure our copy is modifiable.
		this.modifiableJunctionPoints = new IntArrayList(junctionPoints);
	}

	public short z(int i) {
		return z.getShort(i);
	}

	public void setJunctionPoint(int jpIndex, int x) {
	  // These two checks are new as of 15 April 2013.
		Preconditions.checkArgument(jpIndex == 0 || x > modifiableJunctionPoints.getInt(jpIndex - 1));
		Preconditions.checkArgument(jpIndex == modifiableJunctionPoints.size() - 1
				|| x < modifiableJunctionPoints.getInt(jpIndex + 1));
		modifiableJunctionPoints.set(jpIndex, x);
	}

	public String filename() {
		return junctionPointsFile.getFileName().toString();
	}

	@Override
	public String toString() {
		return new ToStringBuilder(this, ToStringStyle.SIMPLE_STYLE).append("junctionPointsFile",
				junctionPointsFile.getFileName().toString()).append("zLength", z.size()).toString();
	}

	public short minZ() {
		return CommonThings.min(z);
	}

	public short maxZ() {
		return CommonThings.max(z);
	}

	public int zLength() {
		return z.size();
	}

	public void save() {
		try {
			JpHelper.writeToFile(modifiableJunctionPoints, junctionPointsFile);
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}
}
